/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
 *
 */

import { FileSet } from '@ohos/hvigor';
import * as path from 'path';

import { BuildArtifactExtension } from '../../const/build-directory-const.js';
import { SignTypeEnum } from '../../enum/sign-type-enum.js';
import { BaseSign } from '../base/base-sign.js';
import { TaskNames } from '../common/task-names.js';
import { TargetTaskService } from '../service/target-task-service.js';
import { SignModel } from '../sign/command-builder-impl/sign-model.js';
import LegacyFATask = TaskNames.LegacyFATask;
import { ModuleTargetData } from '../data/hap-task-target-data.js';

/**
 * 签名bin包
 */
export class LegacySignLiteBin extends BaseSign {
  protected readonly inputFile: string | undefined;
  protected readonly outputFile: string | undefined;
  protected readonly targetServiceData: ModuleTargetData | undefined;

  constructor(taskService: TargetTaskService) {
    super(taskService, TaskNames.LegacyFATask.SIGN_LITE_BIN, SignTypeEnum.BIN);

    // keep same name for .bin
    this.inputFile = path.resolve(this.pathInfo.getModuleBinOutput(), this.targetData.getModuleTargetOutputFileName('', false, BuildArtifactExtension.DOT_BIN));

    this.outputFile = path.resolve(this.pathInfo.getModuleBinOutput(), this.targetData.getModuleTargetOutputFileName('', true, BuildArtifactExtension.DOT_BIN));

    this.targetServiceData = this.targetService.getTargetData();
  }

  declareInputFiles(): FileSet {
    const fileSet = super.declareInputFiles();

    // debug模式下需要打bin包，release模式下不需要
    if (this.targetService.needPackBin(this.targetServiceData!)) {
      return fileSet.addEntry(this.inputFile!, { isDirectory: false });
    }
    return fileSet;
  }

  declareOutputFiles(): FileSet {
    const fileSet = super.declareOutputFiles();
    if (this.outputFile) {
      fileSet.addEntry(this.outputFile, { isDirectory: false });
    }
    return fileSet;
  }

  taskShouldDo(): boolean {
    // debug模式下需要对bin包进行签名
    return this.targetService.needPackBin(this.targetServiceData!);
  }

  initTaskDepends() {
    this.declareDepends(LegacyFATask.GENERATE_LITE_CODE.name);
  }

  protected async doTaskAction(): Promise<void> {
    await this.signUtil.sign(new SignModel(SignTypeEnum.BIN, this.inputFile!, this.outputFile!), this.durationEvent);
  }
}
